package main

import (
	"bufio"
	"flag"
	"fmt"
	"golang.org/x/net/websocket"
	"log"
	"os"
	"os/signal"
	"strconv"
	"time"
)

var origin = "http://localhost/"

//var url = "ws://134.175.146.136:8081/ws/"
var url = "ws://localhost:8081/ws/"

type Message struct {
	From string `json:"from"`
	To   string `json:"to"`
	Body string `json:"body"`
}

func main() {
	flag.Parse()
	args := flag.Args()

	if len(args) != 1 {
		log.Fatal("启动参数后面需要room号")
		return
	}
	room := args[0]

	chs := make([]chan bool, 100)
	for i := 0; i < 100; i++ {
		conn, err := websocket.Dial(url+room, "", origin)
		if err != nil {
			log.Fatal(err)
		}
		chs[i] = make(chan bool)
		go handler(conn, i, chs[i])
	}

	c := make(chan os.Signal)
	//监听指定信号 ctrl+c kill
	signal.Notify(c, os.Interrupt, os.Kill)
	//阻塞直至有信号传入
	<-c
	for _, ch := range chs {
		<-ch
	}
	time.Sleep(time.Second * 10)
	fmt.Println("退出")

}

func handler(conn *websocket.Conn, i int, chOver chan bool) {

	defer conn.Close()
	_, err := conn.Write([]byte("机器人:" + strconv.Itoa(i)))
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			//等待消息
			buf := make([]byte, 256*1000)
			r := bufio.NewReader(conn)
			n, err := r.Read(buf)
			if err != nil {
			}
			fmt.Println(string(buf[:n]))
		}
	}()

	chOver <- true

}
